<template>
  <div>
    <el-steps :active="active" align-center class="AnalysisSteps">
      <el-step :title="$t('工程解析规则')" icon="el-icon-upload"></el-step>
      <el-step :title="$t('开始解析')" icon="el-icon-monitor"></el-step>
    </el-steps>
    <div v-if="inAnalysis" class="AnalysisContent">
      <el-descriptions class="AnalysisDescriptions" :column="1" size="small" border>
        <el-descriptions-item>
          <template slot="label">{{$t('请选择文件')}}</template>
          <el-upload class="upload-Upgrade" ref="upload" :action="global + '/engineering/upload'" :on-success="handleAvatar" :on-error='handleAvatar' accept='.PCZ' :show-file-list='false' :before-upload="fileBeforeUpload" :on-change="handleChange" :headers='headerConfig' :multiple='false' :file-list="fileList" :on-remove='removeFile'>
            <el-button slot="trigger" size="mini" type="primary" class="selectNews">{{$t('选取文件')}}</el-button>
          </el-upload>
        </el-descriptions-item>
        <el-descriptions-item v-if="fileName">
          <template slot="label">{{$t('已上传文件名称')}}</template>
          {{ fileName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">{{$t('请选择源对象')}}
            <el-tooltip class="item" effect="light" :content="$t('提示信息：请选择资源对象中配置的地址或者地址组（可为空）')" placement="top">
              <i class="el-icon-warning-outline" style="color:#E6A23C;font-size:16px;"></i>
            </el-tooltip>
          </template>
          <el-select v-model="record.src" :placeholder="$t('对象[组]')" ref="src" size="mini" clearable>
            <el-option v-for="item in srcList" :key="item.name" :label="item.nameShow" :value="item.name">
            </el-option>
          </el-select>
        </el-descriptions-item>
      </el-descriptions>
      <div class="AnalysisButton">
        <el-button slot="trigger" size="small" type="success" :loading='loading' @click="startAnalysis" class="startAnalysis">{{$t('开始解析')}}</el-button>
      </div>
    </div>
    <div v-else>
      <div style="margin-bottom:20px;">
        <el-button type="info" plain icon="el-icon-arrow-left" size="small" @click="goBack" class="goBack"></el-button>
        <el-button type="primary" size="small" @click="allSelect" class="allSelect">{{$t('全选')}}</el-button>
        <el-button type="success" size="small" @click="saveUserMenu" class="sumbit">{{$t('提交')}}</el-button>
      </div>
      <el-tree :props="props" class="fileCliTree" ref="fileCliTree" :data="fileCliList" node-key="desc" :indent='22' show-checkbox @check-change="handleCheckChange">
      </el-tree>
    </div>
  </div>
</template>
<script>

import { engineeringAnalysis, engineeringUpdate } from '@/api/safe/access/analysis'
import { getAddrGroupArray } from '@/api/list/addr-group'
import { getAddrArray } from '@/api/list/addr'
import { getSessionId } from '@/utils/auth'
import global from '@/global'
import { selectClass } from '@/utils/input-class.js'
export default {
  name: 'Analysis',
  data () {
    return {
      fileList: [], // 文件列表
      srcList: [], // 对象列表
      fileCliList: [], // 树列表
      fileName: '',
      active: 1,
      loading: false,
      inAnalysis: true, // 控制进度
      record: {
        path: '', // /tmp/FC72test.PCZ
        src: ''
      },
      headerConfig: {
        'session_id': getSessionId()
      },
      global: global.BASE_URL,
      props: {
        label: 'desc',
        children: 'next'
      },
      checkedData: []
    }
  },
  created () {
    getAddrArray().then(response => {
      if (response.status === 0) {
        // this.srcList.push({
        //   label: '对象',
        //   options: response.info
        // })
        getAddrGroupArray().then(res => {
          if (res.status === 0) {
            // this.srcList.push({
            //   label: '对象组',
            //   options: res.info
            // })
            for (let item of response.info) {
              item.nameShow = this.$t('地址-') + item.name
              this.srcList.push(item)
            }
            for (let item of res.info) {
              item.nameShow = this.$t('地址组-') + item.name
              this.srcList.push(item)
            }
          }
        })
      }
    })
  },
  mounted () {
    this.$nextTick(() => {
      const selectData = ['src']
      selectClass(this.$refs, selectData)
    })
  },
  methods: {
    // 工程解析方法
    handleChange (file, fileList) {
      const isPCZ = file.name.indexOf('.PCZ') >= 0
      const isLt1M = file.size / 1024 / 1024 / 10 < 1
      if (!isLt1M) {
        fileList.splice(-1, 1)
        this.fileList = fileList
      } else if (!isPCZ) {
        fileList.splice(-1, 1)
        this.fileList = fileList
      } else {
        if (fileList.length > 1) {
          fileList.splice(0, 1)
        }
        this.fileList = fileList
      }
      return isPCZ && isLt1M
    },
    fileBeforeUpload (file) {
      const isPCZ = file.name.indexOf('.PCZ') >= 0
      const isLt1M = file.size / 1024 / 1024 / 10 < 1
      if (!isLt1M) {
        this.$messages.error(this.$t('上传的文件大小不能超过 10MB!'))
        this.$refs.upload.abort()
      } else if (!isPCZ) {
        this.$messages.error(this.$t('上传的文件只能是 PCZ 格式!'))
        this.$refs.upload.abort()
      }
      return isPCZ && isLt1M
    },
    removeFile () {
      this.fileList = []
      this.fileName = ''
      this.record.path = ''
    },
    handleAvatar (res, file) {
      if (res.status === 0) {
        this.fileName = file.name
        this.record.path = res.dir
      } else {
        this.$messages.error(res.msg || this.$t('上传失败'))
      }
    },
    startAnalysis () {
      if (this.record.path) {
        this.loading = true
        engineeringAnalysis(this.record).then(res => {
          if (res.status === 0) {
            this.fileCliList = res.info
            this.inAnalysis = false
            this.active = 2
            this.removeFile()
            this.$nextTick(() => {
              this.allSelect()
            })
          }
          this.loading = false
        }).catch(er => {
          // console.log(er)
          this.active = 1
          this.loading = false
          this.removeFile()
        })
      } else {
        this.$messages.error(this.$t('请上传文件'))
      }
    },
    // 已解析文件方法
    handleCheckChange () {
      this.checkedData = this.$refs.fileCliTree.getCheckedKeys(false).concat(this.$refs.fileCliTree.getHalfCheckedKeys(false))
    },
    goBack () {
      this.inAnalysis = true
      this.active = 1
      this.fileCliList = []
      this.fileName = ''
      this.record = {
        path: '',
        src: ''
      }
    },
    allSelect () {
      this.$refs.fileCliTree.setCheckedNodes(this.fileCliList)
    },
    saveUserMenu () {
      if (this.checkedData.length > 0) {
        let formData = JSON.parse(JSON.stringify(this.fileCliList))
        this.submitFormData(formData)
        engineeringUpdate({ checkedData: JSON.stringify(formData) }).then(res => {
          if (res.status === 0) {
            this.$message({
              message: this.$t(res.msg),
              type: 'success'
            })
            this.goBack()
          }
        })
      } else {
        this.$messages.error(this.$t('请至少选择一条数据'))
      }
    },
    submitFormData (listData) {
      for (let i = listData.length - 1; i >= 0; i--) {
        if (listData[i].next && listData[i].next.length > 0) {
          this.submitFormData(listData[i].next)
        }
        if (!this.checkedData.includes(listData[i].desc)) {
          delete listData.splice(i, 1)
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.AnalysisContent {
  width: 700px;
  margin: 0 auto;
  overflow-x: auto;
}

.AnalysisSteps {
  margin-bottom: 40px;
}

.AnalysisDescriptions {
  width: 400px;
  margin: 0 auto;
}

.AnalysisButton {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}
</style>
